package com.ziyun.erp.modules.production.service.impl;

import com.utility.New;
import com.ziyun.erp.common.e.DeleteEnum;
import com.ziyun.erp.common.e.otherAccessory.OtherAccessoryTypeEnum;
import com.ziyun.erp.common.utils.ErpOrderUtils;
import com.ziyun.erp.modules.order.entity.ErpOrderAllotRelevanceEntity;
import com.ziyun.erp.modules.order.entity.ErpOrderEntity;
import com.ziyun.erp.modules.order.entity.OrderInfoEntity;
import com.ziyun.erp.modules.order.entity.OrderItemEntity;
import com.ziyun.erp.modules.order.service.*;
import com.ziyun.erp.modules.order.vo.OrderItemVo;
import com.ziyun.erp.modules.production.dto.OrderItemSendPicsDto;
import com.ziyun.erp.modules.production.dto.ProcurementItemUpdateDto;
import com.ziyun.erp.modules.production.entity.vo.ErpOrderItemAllotVo;

import com.ziyun.erp.modules.otherAccessory.entity.OtherAccessoryEntity;
import com.ziyun.erp.modules.otherAccessory.service.OtherAccessoryService;
import com.ziyun.erp.modules.production.vo.ErpOrderItemListVo;
import io.renren.common.utils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import com.ziyun.erp.modules.production.dao.ErpOrderItemDao;
import com.ziyun.erp.modules.production.entity.ErpOrderItemEntity;
import com.ziyun.erp.modules.production.service.ErpOrderItemService;
import org.springframework.transaction.annotation.Transactional;


@Service("erpOrderItemService")
public class ErpOrderItemServiceImpl extends ServiceImpl<ErpOrderItemDao, ErpOrderItemEntity> implements ErpOrderItemService {

    @Autowired
    private OtherAccessoryService otherAccessoryService;
    @Autowired
    private ErpOrderLogService erpOrderLogService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private ErpOrderService erpOrderService;
    @Autowired
    private ErpOrderAllotRelevanceService erpOrderAllotRelevanceService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<ErpOrderItemEntity> page = this.selectPage(
                new Query<ErpOrderItemEntity>(params).getPage(),
                new EntityWrapper<ErpOrderItemEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<ErpOrderItemAllotVo> selectErpOrderItemAllotVosByNo(String orderNo) {
        return baseMapper.selectErpOrderItemAllotVosByNo(orderNo);
    }

    /**
     * 根据 erp单号 查询 商品明细
     * @param orderNo
     * @return
     */
    @Override
    public List<ErpOrderItemEntity> selectListByErpOrder(String orderNo) {
        return baseMapper.selectList(new EntityWrapper<ErpOrderItemEntity>()
                .eq("order_no",orderNo)
                .eq("item_del",DeleteEnum.NOT_DELETE.toInt()));
    }

    /**
     * 查询订单商品总金额
     * @param orderNo
     * @return
     */
    @Override
    public BigDecimal selectItemTotalMoney(String orderNo) {
        return baseMapper.selectItemTotalMoney(orderNo);
    }

    @Override
    public boolean operateErpOrderItemStatus(String orderId, Integer status) {
        int selectCount = this.selectCount(new EntityWrapper<>(new ErpOrderItemEntity())
                .eq("order_no", orderId)
                .notIn("status", status)
                .eq("item_del", DeleteEnum.NOT_DELETE.toInt())
        );
        if (selectCount == 0){
            return true;
        }
        return false;
    }

    @Override
    public boolean updateByMap(Map<String, Object> updateMap, Integer eoItemId) {
        int count = baseMapper.updateByMap(updateMap, eoItemId);
        if (count == 0){
            return false;
        }
        return true;
    }

    @Override
    public boolean updateBatchByMap(Map<String, Object> updateMap, List<Integer> eoItemIds) {
        int count = baseMapper.updateBatchByMap(updateMap, eoItemIds);
        if (count == 0){
            return false;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R sendPics(OrderItemSendPicsDto orderItemSendPicsDto) {
        OtherAccessoryEntity otherAccessory = orderItemSendPicsDto.getOtherAccessory();
        otherAccessory.setType(OtherAccessoryTypeEnum.SEND_PICS.toInt());
        otherAccessoryService.insert(otherAccessory);

        ErpOrderItemEntity erpOrderItem = this.baseMapper.selectById(orderItemSendPicsDto.getEoItemId());
        String sendPics = erpOrderItem.getSendPics();
        Map<String, Object> updateMap = new HashMap<>();
        if (StringUtils.isBlank(sendPics)){
            updateMap.put("sendPics", otherAccessory.getId());
        }else {
            updateMap.put("sendPics", sendPics + "," + otherAccessory.getId());
        }
        this.baseMapper.updateByMap(updateMap, erpOrderItem.getEoItemId());
        return R.ok();
    }

    @Override
    public ErpOrderItemEntity selectByItemId(Integer itemId) {
        return this.baseMapper.selectByItemId(itemId);
    }

    @Override
    public boolean updateBatchByOrderItemId(Map<String, Object> updateMap, List<Integer> itemIds) {
        int count = baseMapper.updateBatchByOrderItemId(updateMap, itemIds);
        if (count == 0){
            return false;
        }
        return true;
    }

    @Override
    public boolean updateByMapOrderId(Map<String, Object> updateMap, String orderId) {
        int count = this.baseMapper.updateByMapOrderId(updateMap, orderId);
        if (count == 0){
            return false;
        }
        return true;
    }

    @Override
    public List<ErpOrderItemListVo> selectListByOrderId(String orderNo) {
        return this.baseMapper.selectListByOrderId(orderNo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R procurementItemUpdate(ProcurementItemUpdateDto procurementItemUpdateDto) {
        BigDecimal new_amount = procurementItemUpdateDto.getAmount();
        if (new_amount.compareTo(BigDecimal.ZERO) <= 0){
            return R.error("商品金额应大于0");
        }
        BigDecimal new_price = procurementItemUpdateDto.getPrice();
        BigDecimal new_nums = procurementItemUpdateDto.getNums();

        Integer itemId = procurementItemUpdateDto.getItemId();
        OrderItemEntity orderItem = orderItemService.selectById(itemId);
        BigDecimal old_amount = orderItem.getAmount();
        BigDecimal old_price = orderItem.getPrice();
        BigDecimal old_nums = orderItem.getNums();

        Long orderId = procurementItemUpdateDto.getOrderId();
        OrderInfoEntity orderInfo = orderInfoService.selectById(orderId);
        BigDecimal old_totalAmount = orderInfo.getTotalAmount();
        BigDecimal old_payableAmount = orderInfo.getPayableAmount();
        BigDecimal new_totalAmount = old_totalAmount.subtract(old_amount).add(new_amount);
        BigDecimal new_payableAmount = old_payableAmount.subtract(old_totalAmount).add(new_totalAmount);
        ErpOrderItemEntity erpOrderItem = this.selectByItemId(itemId);
        boolean createErpOrder = false;
        if (erpOrderItem == null){
            ErpOrderEntity erpOrderEntity = ErpOrderUtils.ziyunOrderToErp(orderInfo);
            erpOrderEntity.setTotalAmount(new_totalAmount);
            erpOrderEntity.setPayableAmount(new_payableAmount);
            erpOrderService.insert(erpOrderEntity);

            List<OrderItemEntity> orderItemEntityList = orderItemService.selectByOrderId(orderId);
            List<ErpOrderItemEntity> erpOrderItemEntityList = ErpOrderUtils.ziyunOrderItemToErp(orderItemEntityList, orderId.toString());
            for (ErpOrderItemEntity erpOrderItemEntity : erpOrderItemEntityList){
                Integer originalItemId = erpOrderItemEntity.getOriginalItemId();
                if (itemId.intValue() == originalItemId.intValue()){
                    erpOrderItemEntity.setAmount(new_amount);
                    erpOrderItemEntity.setPrice(new_price);
                    erpOrderItemEntity.setNums(new_nums);
                }
            }
            this.insertBatch(erpOrderItemEntityList);
            createErpOrder = true;
        }
        Map<String, Object> itemUpdateMap = New.hashMap(3);
        itemUpdateMap.put("amount", new_amount);
        itemUpdateMap.put("price", new_price);
        itemUpdateMap.put("nums", new_nums);
        orderItemService.updateByMap(itemUpdateMap, itemId);

        Map<String, Object> orderUpdateMap = New.hashMap(1);
        orderUpdateMap.put("totalAmount", new_totalAmount);
        orderUpdateMap.put("payableAmount", new_payableAmount);
        orderInfoService.updateByMap(orderUpdateMap, orderId.toString());

        if (!createErpOrder){
            List<Integer> itemIds = New.arrayList(1);
            itemIds.add(itemId);
            this.updateBatchByOrderItemId(itemUpdateMap, itemIds);
            erpOrderService.updateByMap(orderUpdateMap, orderId.toString());
        }

        erpOrderLogService.insertOrderItemLog(orderId.toString(), Long.valueOf(itemId),
                "企业集采商品修改：" + "原数量["+ old_nums +"],原价格["+ old_price +"],原小计["+ old_amount +"]");
        return R.ok();
    }

    @Override
    public OrderItemVo getAllotQuoteItem(Integer productionId) {
        ErpOrderAllotRelevanceEntity erpOrderAllotRelevance = erpOrderAllotRelevanceService.selectOne(new EntityWrapper<>(new ErpOrderAllotRelevanceEntity())
                .eq("production_id", productionId)
                .eq("del", DeleteEnum.NOT_DELETE)
        );
        return orderItemService.selectOrderItemVoById(erpOrderAllotRelevance.getItemAllotId());
    }

}
